""" Context processor to show the selected menu option.

It will set the selected menu option as selected and also 
it will search for the sub menues.
"""

from menu.utils import get_user_tree_menu

def get_menu(request):
    """ It will return the menu that should be shown.
    It will take the users permissions (admin, anonymus, etc...) and
    the option that the user selected.

    It will return a list of lists. For example:
        [ 
            [MainOption1, MainOption2, MainOption3],
            [SubOption1Option3, SubOption2Option3, SubOption3Option3],
            ....
        ]
    Where the first value will be the main menu. The second option wil be
    sub menu of the option that the user choose in the main menu... And so on..

    :parameters:
        user:
            the user using the application
        option_selected:
            the option that the user choose.
    
    :returns:
        the menu that should be shown to the user.
    """
    tree = get_user_tree_menu(request.user)
    
    # para tener en cuenta cuando todavia no se tiene ningun
    # menu entry cargado...
    if not tree:
        return dict()
    result = [tree[0]]
    url = request.path
    selected_entry = get_selected_option(url, tree[0])
    if not selected_entry:
        selected_entry = tree[0][0]

    children = selected_entry.children
    while children:   
        result.append(children)
        selected_entry = get_selected_options(url, children)
        if selected_entry:
            children =  selected_entry.children
    
    return {'menu': result}

def get_selected_option(url, menu_entries):
    """ It will return the selected option of the menu.
    For this it will use the request url and the urls of the menus entrys.
   
    
    :parameters:
        url: str
            the url that the user is viewing
        menu_entries: list(MenuEntry)
            one of the options that the user may select.
    
    
    :return:
        if the url belongs to one of that menu_entries then it returns
        that menu, else None.
    """
    for entry in menu_entries:
        if url.beginswith(entry.url):
            return entry
    return entry

